<?php
namespace app\controllers;

include_once "../common/corelib/wx/wxBizDataCrypt.php";

use app\common\corelib\CacheHelper;
use app\common\corelib\LocalUpload;
use app\logic\ShopLogic;
use app\logic\UserLogic;
use app\common\corelib\alidayu\api_demo\SmsDemo;
use Yii;
use WXBizDataCrypt;


class UserController extends BaseController
{

    /**
     * 获取openid
     * @apiDescription   by Jim
     * @api              {post} /user/get-openid 获取openid
     * @apiName          get-openid
     * @apiVersion       1.0.0
     * @apiParam {string} code  临时登录凭证code
     * @apiGroup         User
     * @apiSampleRequest /user/get-openid?flagsign=1
     * @apiSuccessExample {json} 获取成功
     * {
    openid	用户唯一标识
    //session_key	会话密钥
    unionid	用户在开放平台的唯一标识符
    }
     * @apiError         none
     */
    public function actionGetOpenid(){
        $code = $this->getQueryparams('code','');
        $appid = Yii::$app->params['wechat']['appid'];
        $app_secret = Yii::$app->params['wechat']['app_secret'];
        $result = file_get_contents("https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$app_secret&js_code=$code&grant_type=authorization_code");
        $arr_result = json_decode($result,true);
        CacheHelper::set('session_key_'.$arr_result['openid'],$arr_result['session_key']);
        $arr_result['session_key']='';
        echo json_encode($arr_result);
    }

    /**
     * 用户手机解密（用户信息解密）
     * @apiDescription   by Jim
     * @api              {post} /user/decode 用户手机解密
     * @apiName          decode
     * @apiVersion       1.0.0
     * @apiParam {string} openid  用户openid
     * @apiParam {string} iv  加密算法的初始向量
     * @apiParam {string} encryptedData  包括敏感数据在内的完整用户信息的加密数据
     * @apiGroup         User
     * @apiSampleRequest /user/decode?flagsign=1
     * @apiSuccessExample {json} 获取成功
     *
     *
     （1） 解密手机号{
    "phoneNumber": "13580006666",
    "purePhoneNumber": "13580006666",
    "countryCode": "86",
    "watermark":
    {
    "appid":"APPID",
    "timestamp":TIMESTAMP
    }
    }
    参数	类型	说明
    phoneNumber	String	用户绑定的手机号（国外手机号会有区号）
    purePhoneNumber	String	没有区号的手机号
    countryCode	String	区号
     （2）解密用户信息返回
     * {
    "openId": "OPENID",
    "nickName": "NICKNAME",
    "gender": GENDER,
    "city": "CITY",
    "province": "PROVINCE",
    "country": "COUNTRY",
    "avatarUrl": "AVATARURL",
    "unionId": "UNIONID",
    "watermark":
    {
    "appid":"APPID",
    "timestamp":TIMESTAMP
    }
    }
     * @apiError         none
     */
    public function actionDecode(){
        $openid = $this->getQueryparams('openid','');
        $iv = $this->getQueryparams('iv','');
        $encryptedData = $this->getQueryparams('encryptedData','');
        $sessionKey = CacheHelper::get('session_key_'.$openid);
        $appid = Yii::$app->params['wechat']['appid'];

        $pc = new WXBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data );

        if ($errCode == 0) {
            echo json_encode($data);
        } else {
            $this->error($errCode,'解密失败');
        }

    }


    /**
     * 授权登录
     * @apiDescription   by Jim
     * @api              {post} /user/login-by-openid 授权登录
     * @apiName          login-by-openid
     * @apiVersion       1.0.0
     * @apiParam {string} open_id  微信openid
     * @apiGroup         User
     * @apiSampleRequest /user/login-by-openid?flagsign=1
     * @apiSuccessExample {json} 获取成功
     * {
    `user_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户id',
    `phone` varchar(255) NOT NULL COMMENT '电话号码',
    `type` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '用户类型：默认0用户，1店主，2店长',
    `current_num` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '体验卡当前有效次数',
    `wechat_name` varchar(255) DEFAULT NULL COMMENT '微信名',
    `head_img` varchar(255) NOT NULL DEFAULT '' COMMENT '头像',
    `city` varchar(255) DEFAULT NULL COMMENT '城市',
    `bind_status` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '绑定状态',
    `bind_time` datetime DEFAULT NULL COMMENT '绑定时间',
    `create_time` datetime NOT NULL COMMENT '创建时间',
    `status` tinyint(1) unsigned NOT NULL DEFAULT '1' COMMENT '状态',
    `open_id` varchar(255) DEFAULT NULL COMMENT '微信openid',
     access_token

     }
     * @apiError         100002 未绑定手机，跳转到绑定手机的页面
     * @apiError         100005 合同已到期，请联系管理员
     */
    public function actionLoginByOpenid(){
        $open_id = $this->getQueryparams('open_id','');
        $userLogic = new UserLogic();
        if($user=$userLogic->getUserByOpenid($open_id)){
            if($user['status']==0)
                $this->error('100009','该账号无效，请联系管理员');
            if($user['type']==1){
                $shopLogic = new ShopLogic();
                $shopList = $shopLogic->getShopListByOwner($user['user_id']);
                $canlogin = false;
                foreach($shopList AS $key=>$value){
                    if($value['contract_start_time']<=date('Y-m-d H:i:s') && $value['contract_end_time']>=date('Y-m-d H:i:s'))
                        $canlogin = true;
                }
                if(!$canlogin)
                    $this->error('100005','合同已到期，请联系管理员');
            }elseif($user['type']==2){
                $userLogic = new UserLogic();
                $manager = $userLogic->getManager($user['user_id']);

                $canlogin = false;
                if($manager['contract_start_time']<=date('Y-m-d H:i:s') && $manager['contract_end_time']>=date('Y-m-d H:i:s'))
                    $canlogin = true;
                if(!$canlogin)
                    $this->error('100005','合同已到期，请联系管理员');
            }
            CacheHelper::set('user_id_'.$user['user_id'],$user);
            $token = MD5($user['user_id'] . $user['phone'] . time());
            CacheHelper::set('user_token_'.$token,$user);
            $user['access_token'] = $token;
            $this->response($user);
        }else{
            $this->error('100002','尚未绑定手机，请绑定手机');
        }
    }
    /**
     * 发送短信验证码
     * @apiDescription   by Jim
     * @api              {post} /user/get-vercode 发送短信验证码
     * @apiName          get-vercode
     * @apiVersion       1.0.0
     * @apiParam {string} phone  电话
     * @apiGroup         User
     * @apiSampleRequest /user/get-vercode?flagsign=1
     * @apiSuccessExample {json} 获取成功
     * {

    }

     * @apiError
     */
    public function actionGetVercode(){
        /*CacheHelper::set('vercode_123','123',600);
        var_dump(CacheHelper::get('vercode_123'));exit;*/
        $mobile = $this->getQueryparams('phone','');
        if(!preg_match("/^1[3456789]{1}\d{9}$/",$mobile)){
            $this->error('100001','请输入正确的手机号码');
        }
        if(!$vercode = CacheHelper::get('vercode_'.$mobile)){
            $vercode = $this->_generate_code(6);
        }

        /*$response = SmsDemo::sendSms(
            "儿嬉创享空间", // 短信签名
            "SMS_133266053", // 短信模板编号
            $mobile, // 短信接收者
            Array(  // 短信模板中字段的值
                "code"=>$vercode,
                "product"=>"dt"
            )
        );*/
        $response = SmsDemo::sendSms(
            "儿嬉创享空间", // 短信签名
            "SMS_131785157", // 短信模板编号
            $mobile, // 短信接收者
            Array(  // 短信模板中字段的值
                "code"=>$vercode,
                "product"=>"dt"
            )
        );
        //$result = json_decode($response,true);

        if($response->Code=='OK'){
            CacheHelper::set('vercode_'.$mobile,$vercode,600);
        }

        $this->response($response);
    }

    private function _generate_code($length = 4) {
        $min = pow(10 , ($length - 1));
        $max = pow(10, $length) - 1;
        return rand($min, $max);
    }

    /**
     * 绑定手机并登录
     * @apiDescription   by Jim
     * @api              {post} /user/bind 绑定手机并登录
     * @apiName          bind
     * @apiVersion       1.0.0
     * @apiParam {string} open_id  微openid信
     * @apiParam {string} phone  电话
     * @apiParam {string} vercode  验证码
     * @apiParam {string} wechat_name  微信名
     * @apiParam {string} head_img  头像
     * @apiParam {string} gender  性别，0未知，1男性，2女性
     * @apiParam {string} city  城市
     * @apiGroup         登录模块
     * @apiSampleRequest /user/bind?flagsign=1
     * @apiSuccessExample {json} 获取成功
     * {
    `user_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户id',
    `phone` varchar(255) NOT NULL COMMENT '电话号码',
    `type` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '用户类型：默认0用户，1店主，2店长',
    `current_num` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '体验卡当前有效次数',
    `wechat_name` varchar(255) DEFAULT NULL COMMENT '微信名',
    `head_img` varchar(255) NOT NULL DEFAULT '' COMMENT '头像',
     `gender` tinyint(1) DEFAULT NULL COMMENT '性别',
    `city` varchar(255) DEFAULT NULL COMMENT '城市',
    `bind_status` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '绑定状态',
    `bind_time` datetime DEFAULT NULL COMMENT '绑定时间',
    `create_time` datetime NOT NULL COMMENT '创建时间',
    `status` tinyint(1) unsigned NOT NULL DEFAULT '1' COMMENT '状态',
    `open_id` varchar(255) DEFAULT NULL COMMENT '微信openid',
     access_token

    }

     * @apiError  100003 验证码失效；100004验证码出错；100005失败
     */
    public function actionBind(){
        $open_id = $this->getQueryparams('open_id','');
        $phone = $this->getQueryparams('phone','');
        $vercode = $this->getQueryparams('vercode','');
        $wechat_name = $this->getQueryparams('wechat_name','');
        $head_img = $this->getQueryparams('head_img','');
        $gender = $this->getQueryparams('gender',0);
        $city = $this->getQueryparams('city','');
        $userLogic = new UserLogic();
        $user = $userLogic->getUserByPhone($phone);
        if($user && $user->type!=0)
            $this->error('100010','合伙人帐号无法登陆');
        if($cache_vercode = CacheHelper::get('vercode_'.$phone)){
            if($vercode==$cache_vercode){

                $user = $userLogic->bind($phone,$open_id,$wechat_name,$head_img,$gender,$city);
                if($user){
                    CacheHelper::set('user_id_'.$user->user_id,$user);
                    $token = MD5($user->user_id . $user->phone . time());
                    CacheHelper::set('user_token_'.$token,$user);
                    $user = $user->toArray();
                    $user['access_token'] = $token;
                    $this->response($user);
                }
                else{
                    $this->error('100009','该手机号无效，请联系管理员');
                }
            }else{
                $this->error('100004','验证码错误，请重新输入');
            }
        }else{
            $this->error('100003','验证码失效，请重新发送验证码');
        }
    }
    /**
     * 手机登录
     * @apiDescription   by Jim
     * @api              {post} /user/login 手机登录
     * @apiName          bind
     * @apiVersion       1.0.0
     * @apiParam {string} phone  电话
     * @apiParam {string} vercode  验证码
     * @apiGroup         User
     * @apiSampleRequest /user/login?flagsign=1
     * @apiSuccessExample {json} 获取成功
     * {
    `user_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户id',
    `phone` varchar(255) NOT NULL COMMENT '电话号码',
    `type` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '用户类型：默认0用户，1店主，2店长',
    `current_num` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '体验卡当前有效次数',
    `wechat_name` varchar(255) DEFAULT NULL COMMENT '微信名',
    `head_img` varchar(255) NOT NULL DEFAULT '' COMMENT '头像',
    `city` varchar(255) DEFAULT NULL COMMENT '城市',
    `bind_status` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '绑定状态',
    `bind_time` datetime DEFAULT NULL COMMENT '绑定时间',
    `create_time` datetime NOT NULL COMMENT '创建时间',
    `status` tinyint(1) unsigned NOT NULL DEFAULT '1' COMMENT '状态',
    `open_id` varchar(255) DEFAULT NULL COMMENT '微信openid',
    access_token:
    }

     * @apiError  100003 验证码失效；100004验证码出错；100005失败
     */
    public function actionLogin(){
        $phone = $this->getQueryparams('phone','');
        $vercode = $this->getQueryparams('vercode','');
        if($cache_vercode = CacheHelper::get('vercode_'.$phone)){
            if($vercode==$cache_vercode){
                $userLogic = new UserLogic();
                $result = $userLogic->login($phone);
                $user = $result['user'];
                if(!$result['is_new']){
                    /*if($user['type']==0)
                        $this->error('100005','该账号无效，请联系管理员');*/
                    if($user['type']==1){
                        $shopLogic = new ShopLogic();
                        $shopList = $shopLogic->getShopListByOwner($user['user_id']);
                        $canlogin = false;
                        foreach($shopList AS $key=>$value){
                            if($value['contract_start_time']<=date('Y-m-d H:i:s') && $value['contract_end_time']>=date('Y-m-d H:i:s'))
                                $canlogin = true;
                        }
                        if(!$canlogin)
                            $this->error('100005','合同已到期，请联系管理员');
                    }elseif($user['type']==2){
                        $userLogic = new UserLogic();
                        $manager = $userLogic->getManager($user['user_id']);
                        $canlogin = false;
                        if($manager['contract_start_time']<=date('Y-m-d H:i:s') && $manager['contract_end_time']>=date('Y-m-d H:i:s'))
                            $canlogin = true;
                        if(!$canlogin)
                            $this->error('100005','合同已到期，请联系管理员');
                        $user['shop_id'] = $manager['shop_id'];
                        $user['on_work'] = $manager['on_work'];
                    }
                }
                CacheHelper::set('user_id_'.$user['user_id'],$user);
                $token = MD5($user['user_id'] . $user['phone'] . time());
                CacheHelper::set('user_token_'.$token,$user);
                $user['access_token'] = $token;
                $this->response($user);
            }else{
                $this->error('100004','验证码错误，请重新输入');
            }
        }else{
            $this->error('100003','验证码失效，请重新发送验证码');
        }
    }
    /**
     * 退出登录
     * @apiDescription   by Jim
     * @api              {post} /user/logout 退出登录
     * @apiName          cancel-order
     * @apiVersion       1.0.0
     * @apiParam {string} access_token
     * @apiGroup         User
     * @apiSampleRequest /user/logout?flagsign=1
     * @apiSuccessExample {json} 获取成功
     * {

    }
     * @apiError         100006
     */
    public function actionLogout(){
        $aceess_token = $this->getQueryparams('aceess_token','');
        $userLogic = new UserLogic();
        $user = $userLogic->getUser($this->user_id);
        if($user){
            CacheHelper::del('user_id_'.$user->user_id);
            CacheHelper::del('user_token_'.$aceess_token);
            $this->response();
        }
        else{
            $this->error('100006','FAIL');
        }

    }
    /**
     * 上班
     * @apiDescription   by Jim
     * @api              {post} /user/on-duty 上班
     * @apiName          on-duty
     * @apiVersion       1.0.0
     * @apiParam {int} shop_id 商店id
     * @apiParam {string} access_token
     * @apiGroup         User
     * @apiSampleRequest /user/on-duty?flagsign=1
     * @apiSuccessExample {json} 获取成功
     * {

    }
     * @apiError         100006 fail, 100007不是店长
     */
    public function actionOnDuty(){
        $shop_id = $this->getQueryparams('shop_id',0);
        $userLogic = new UserLogic();
        $user = $userLogic->getUser($this->user_id);
        if($user->type!=2)
            $this->error('100007','不是店长不能On Duty');
        $result = $userLogic->OnDuty($this->user_id,$shop_id);
        if($result!==false){
            $this->response(['on_work'=>$result]);
        }else{
            $this->error('100006','已经有人上班');
        }
    }



	


}